package com.rchat.pocmini.activity.chatmessage;

import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;

import com.airtalkee.sdk.entity.AirContact;
import com.airtalkee.sdk.entity.AirMessage;
import com.airtalkee.sdk.entity.AirSession;
import com.rchat.pocmini.R;
import com.rchat.pocmini.activity.listener.MessageListener;
import com.rchat.pocmini.activity.listener.MessagePttListener;
import com.rchat.pocmini.activity.view.MessageRecordingView;
import com.rchat.pocmini.bean2eventbus.MessageListenerBean;
import com.rchat.pocmini.bean2eventbus.MessagePttListenerBean;
import com.rchat.pocmini.message.PocAirtalkeeMessage;
import com.rchat.pocmini.service.PocService;
import com.rchat.pocmini.session.PocAirtalkeeSessionManager;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import static android.content.Context.VIBRATOR_SERVICE;

/**
 * Created by 59450 on 2017/9/28.
 */

public class ChatMessagePresenterImpl extends ChatMessageContract.Presenter implements MessageListener,MessagePttListener {

    private int currentPage = 1; //默认在第一页
    private static final int LINE_SIZE = 20;    //每次显示数
    private int allMessageCount = 0;  //全部记录数
    private int pageSize = 1;  //默认共一页

    private PocAirtalkeeMessage pocAirtalkeeMessage;
    private boolean isAutoPlayNextRecord;

    //录音
    private float startY = 0.0F;
    private boolean recordCancel = false;
    private AirMessage currentAirMsg;
    private AirMessage nextAirMsg;

    private String groupId;

    @Override
    public void onPStart() {
        super.onPStart();
        pocAirtalkeeMessage = PocAirtalkeeMessage.getPocAirtalkeeMessageInstance();
        //注册MessageListener
        MessageListenerBean b1 = new MessageListenerBean();
        b1.setTarget(this.getClass(), PocService.class,"onEventBusUpdateMessageListener");
        b1.setCurrentEvent(MessageListenerBean.EVENT_REGISTER_LISTENER);
        b1.setListener(this);
        EventBus.getDefault().post(b1);

        //注册MessagePttListener
        MessagePttListenerBean b2 = new MessagePttListenerBean();
        b2.setTarget(this.getClass(),PocService.class,"onEventBusUpdateMessagePttListener");
        b2.setCurrentEvent(MessagePttListenerBean.EVENT_REGISTER_LISTENER);
        b2.setListener(this);
        EventBus.getDefault().post(b2);
    }

    @Override
    public void onPDestroy() {
        MessageListenerBean b1 = new MessageListenerBean();
        b1.setTarget(this.getClass(), PocService.class,"onEventBusUpdateMessageListener");
        b1.setCurrentEvent(MessageListenerBean.EVENT_UNREGISTER_LISTENER);
        b1.setListener(this);
        EventBus.getDefault().post(b1);

        MessagePttListenerBean b2 = new MessagePttListenerBean();
        b2.setTarget(this.getClass(),PocService.class,"onEventBusUpdateMessagePttListener");
        b2.setCurrentEvent(MessagePttListenerBean.EVENT_UNREGISTER_LISTENER);
        b2.setListener(this);
        EventBus.getDefault().post(b2);
        super.onPDestroy();
    }

    @Override
    void loadFirstPageData(String groupId) {
        this.groupId = groupId;
        allMessageCount = mModel.getAllMessagesCount(mActivity,groupId);
        pageSize = (allMessageCount + LINE_SIZE - 1) / LINE_SIZE;
        List<AirMessage> list = mModel.loadFirstPageData(mActivity,groupId,currentPage,LINE_SIZE);
        mView.showMessage(list);
    }

    @Override
    void messageListScroll(String groupId,AbsListView view, int scrollState) {
        if (currentPage < pageSize && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            int lasPos = view.getFirstVisiblePosition();
            if (lasPos == 0) {
                currentPage++;
                List<AirMessage> list = mModel.loadMessageInfos(mActivity,groupId,currentPage,LINE_SIZE);
                mView.showMessage(list);
                mView.setMessageListSelection(LINE_SIZE -1,true);
            }
        }
    }

    @Override
    void messageSend(String groupId, String content) {
        pocAirtalkeeMessage.messageSend(groupId, content, false, true);
    }

    @Override
    void speakBtnTouch(String groupId, View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            startY = event.getY();
            recordCancel = false;
            if (currentAirMsg != null && currentAirMsg.isRecordPlaying()) {
                pocAirtalkeeMessage.messageRecordPlayStop();
            }
            pocAirtalkeeMessage.messageRecordStart(groupId, true);
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            pocAirtalkeeMessage.messageRecordStop(recordCancel);
            mView.showRecordingView(MessageRecordingView.STOP_TIME, Boolean.valueOf(recordCancel));

        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            if (Math.abs(event.getY() - v.getHeight()) > 100 + v.getHeight()) {
                if (!recordCancel) {
                    mView.showRecordingView(MessageRecordingView.RECORD_CANCEL, 1);
                    recordCancel = true;
                }
            }
            if (recordCancel) {
                if (Math.abs(event.getY()) < startY + 10.0F) {
                    mView.showRecordingView(MessageRecordingView.RECORD_OK, null);
                    recordCancel = false;
                }
            }
        }
    }

    @Override
    void soundMessagePlay(View v) {
        AirMessage airMessage = (AirMessage) v.getTag();
        if (airMessage.getType() == AirMessage.TYPE_RECORD) {
            if (airMessage.getState() == AirMessage.STATE_GENERATING) {
                return;
            }
            if (currentAirMsg != null && currentAirMsg.isRecordPlaying()) {
                if (currentAirMsg.getMessageCode().equals(airMessage.getMessageCode())) {//同一条就停止
                    isAutoPlayNextRecord = false;
                    nextAirMsg = null;
                } else {
                    isAutoPlayNextRecord = true;
                    nextAirMsg = airMessage;
                }

                pocAirtalkeeMessage.messageRecordPlayStop();
            } else {
                isAutoPlayNextRecord = false;
                nextAirMsg = null;
                currentAirMsg = airMessage;
                if (currentAirMsg.getRecordType() == 1) {
                    pocAirtalkeeMessage.messageRecordPlayStartLocal(currentAirMsg);
                } else {
                    pocAirtalkeeMessage.messageRecordPlayStart(currentAirMsg);
                }
            }
        } else if (airMessage.getType() == AirMessage.TYPE_PICTURE) {
        }
    }

    @Override
    void backPressed(String content) {
        AirSession airSession = PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().sessionCall(groupId);
        airSession.setMessageTextDraft(content);
    }

    @Override
    public void onMessageIncomingRecv(boolean b, AirMessage airMessage) {
        if (!airMessage.getSessionCode().equals(groupId)) {
            return;
        }
        mView.showMessage(airMessage);
    }

    @Override
    public void onMessageIncomingRecv(List<AirMessage> list) {
        //登录后会自动收到离线即时消息列表事件
        if(list==null||list.get(0)==null||!list.get(0).getSessionCode().equals(groupId)){
            return;
        }
        mView.showMessage(list);
    }

    @Override
    public void onMessageOutgoingSent(boolean b, AirMessage airMessage, boolean sendSuccess) {
        if (sendSuccess) {
            mView.showMessage(airMessage);
        }
    }

    @Override
    public void onMessageUpdated(AirMessage airMessage) {

    }

    @Override
    public void onMessageRecordStart() {
//        callSystemVibrator();
        mView.showRecordingView(MessageRecordingView.START_RECORD, null);
    }

    @Override
    public void onMessageRecordStop(int arg0, String arg1) {
        mView.showRecordingView(MessageRecordingView.STOP_TIME, Boolean.valueOf(this.recordCancel));
        if (arg0 == -2 || arg0 == -1 || arg0 == -3) {//遇到录制错误移除消息
            mView.removeMessage();
        }
        switch (arg0) {
            case -2:
            case -1:
                mView.showShortToast(R.string.record_time_too_short);
                break;
            case -3:
                mView.showShortToast(R.string.record_cancel);
                break;
        }
    }

    @Override
    public void onMessageRecordTransfered(String s, String s1) {

    }

    @Override
    public void onMessageRecordPlayLoading(String s, String s1) {

    }

    @Override
    public void onMessageRecordPlayLoaded(boolean b, String s, String s1, byte[] bytes) {

    }

    @Override
    public void onMessageRecordPlayStart(String s, String s1) {
        currentAirMsg.setRecordPlaying(true);
        mView.setRecordPlaying(currentAirMsg);

    }

    @Override
    public void onMessageRecordPlayStop(String s, String s1) {
        currentAirMsg.setRecordPlaying(false);
        mView.setRecordPlaying(currentAirMsg);

        if (isAutoPlayNextRecord) {
            currentAirMsg = nextAirMsg;
            isAutoPlayNextRecord = false;
            if (currentAirMsg.getRecordType() == 1) {
                pocAirtalkeeMessage.messageRecordPlayStartLocal(currentAirMsg);
            } else {
                pocAirtalkeeMessage.messageRecordPlayStart(currentAirMsg);
            }
        }

    }

    @Override
    public void onMessagePttRecord(AirSession airSession, AirMessage airMessage, String s, String s1) {
        if (!airMessage.getSessionCode().equals(groupId)) {
            return;
        }
        /**
         * Modify 李锦锻 by 2017/8/14
         * sdk直接返回的airMessage参数通过getInameFrom方法获取的是ipoc id，本来应该是账号的displayName，
         * 通过重新设置airMessage的InameFrom，设置为displayName，解决聊天信息界面显示ipoc id 的bug
         */
        AirContact a = airSession.getSpeaker();
        airMessage.setInameFrom(a.getDisplayName());
        mView.showMessage(airMessage);

    }
//
//    //震动
//    private void callSystemVibrator() {
//        Vibrator vibrator;
//        vibrator = (Vibrator) mActivity.getSystemService(VIBRATOR_SERVICE);
//        vibrator.vibrate(new long[]{0, 150}, -1);
//    }
}
